var deviceone = require("deviceone");
var app = deviceone.sm("do_App");
var nf = deviceone.sm("do_Notification");
var userUtil = require("helper/user");
var commonUrl = require("url/common");
var openHelper = require("helper/open");
var qqCacher = require("helper/qqCacher");
var deviceHelper = require("helper/device");
var imApiHelper = require("helper/imApi");
var dialog = deviceone.sm("do_Dialog");
var timeout = "12000";
var data1,isFlag = false;

/**
 * POST方式请求数据
 * @url:请求地址
 * @param:请求参数(Json对象)
 * @callback:回调函数
 */
module.exports.post = function(url,param,callback,errorCallback){
	var network = deviceone.sm("do_Network");
	var netStatus = network.getStatus();
	if(!netStatus || netStatus==null || "none"===netStatus.toLowerCase()){
		nf.toast("当前没有网络");
		return;
	}
	var http = initHttp(callback,errorCallback);
    http.url = url;
    http.body = param;
    http.request();
};
/**
 * 多文件上传-Form方式提交表单数据
 * @files:需要上传的文件数据(数组方式)
 * @folder:上传后指定的文件夹
 * @callback:回调函数
 */
module.exports.form = function(files,folder,callback,errorCallback){
	var http = initHttp(callback,errorCallback);
	http.url = commonUrl.oss.form;
	http.contentType = "multipart/form-data";
	var fileArr = [];
	if(files && files.length>0){
		for (var int = 0; int < files.length; int++) {
			fileArr.push({"key":"file"+int,"value":files[int]});
		}
	}
	var paramData = {
		"files" : fileArr,
		"texts" : [{
			"key" : "folder",
			"value" : folder
		}]
	};
	http.form(paramData);
};
/**
 * 单文件上传
 * @file:需要上传的文件
 * @folder:上传后指定的文件夹
 * @callback:回调函数
 */
module.exports.upload = function(file,folder,callback,errorCallback){
	var http = initHttp(callback,errorCallback);
    http.url = commonUrl.oss.upload;
    http.upload(file,folder);
};
/**
 * 文件下载
 * @source:下载文件的实际路径
 * @target:下载文件保存的路径(含文件名)
 * @successCb:下载完成后回调函数
 * @failCb:下载失败回调函数
 * @progressCb:下载过程中回调函数
 */
module.exports.download = function(source,target,successCb,failCb,progressCb){
	var http = deviceone.mm("do_Http");
	http.timeout = timeout;
	http.contentType = "application/json";
    http.url = source;
    http.on("success", function(data) {
    	if(successCb && typeof successCb == "function") {
    		successCb(data);
        }else{
        	nf.toast("下载完成");
        }
    });
    http.on("fail", function(data) {
    	if(failCb && typeof failCb == "function") {
    		failCb(data);
        }else{
        	nf.toast("下载失败");
        }
    });
    http.on("progress", function(data) {
    	if(progressCb && typeof progressCb == "function") {
    		progressCb(data);
        }else{
        	nf.toast("下载中");
        }
    });
    http.download(target);
};
function initHttp(callback,errorCallback){
	if(!isFlag){
		isFlag = true;
		dialog.open("source://view/reuse/loading.ui", data1,true,function(data, e){});
	}
	var http = deviceone.mm("do_Http");
    http.method = "POST";
    http.timeout = timeout;
    http.contentType = "application/json";
    var loginToken = "";
    if(userUtil.loginToken()!=="undefined"&&userUtil.loginToken()!==""){
    	loginToken = userUtil.loginToken();
    }
    http.setRequestHeader(userUtil.userLoginTokenKey(),loginToken);
    http.setRequestHeader(userUtil.authKey(), userUtil.authValue());
    var communityVisitId = qqCacher.communityVisitId();
    if(communityVisitId&&communityVisitId!=null&&communityVisitId!==""){
    	http.setRequestHeader(qqCacher.communityVisitIdKey(), communityVisitId);
    }
    
    var nativeVersion = qqCacher.currentNativeVersion();
    if(nativeVersion&&nativeVersion!=null&&nativeVersion!==""){
    	http.setRequestHeader("nativeVer", nativeVersion);
    }
    http.setRequestHeader("contentVer", qqCacher.currentContentVersion());
    http.setRequestHeader("platformCodeStr", deviceHelper.getOsType());
    http.on("result", function(resData){
    	if(isFlag){
    	  isFlag=false;
    	  dialog.close();
    	}
    	if(resData && resData.status==200){
    		var d = JSON.parse(resData.data);
    		if(d.code==1) {
    			if(callback && typeof callback == "function") {
                    callback(d.map);
                }else{
                	if(d.msg&&d.msg!==""&&d.msg!=="undefined"){
                		nf.toast(d.msg);
                	}
                }
            }else{
            	if(d.msg&&d.msg!==""&&d.msg!=="undefined"){
            		nf.toast(d.msg);
            	}
            	if(d.code==2){
            		imApiHelper.logoutIM(function(){
            			openHelper.openLogin();
            		});
            	}else if(d.code==3){
            		openHelper.openRealAuth();
            	}else if(d.code==6){
            		app.fire("fireAppUpgrade",d.map.pubUpgradeVo);
            	}else {
            		if(errorCallback && typeof errorCallback == "function") {
            			errorCallback(d);
                    }
            	}
            }
    	}else{
    		nf.toast("系统繁忙，请稍后再试");
    	}
    }).on("progress", function(resData){
    	if(isFlag){
      	  isFlag=false;
      	  dialog.close();
      	}
    	if(resData){}
    }).on("fail", function(resData){
    	if(isFlag){
      	  isFlag=false;
      	  dialog.close();
      	}
    	var network = deviceone.sm("do_Network");
    	var netStatus = network.getStatus();
    	if(!netStatus || netStatus==null || "none"===netStatus.toLowerCase()){
    		nf.toast("当前没有网络");
    	}else{
    		nf.toast("系统繁忙，请稍后再试");
    	}
    });
    return http;
}